package com.softeem.mpdemo.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.softeem.mpdemo.dto.Result;
import com.softeem.mpdemo.entity.Admin;
import com.softeem.mpdemo.entity.User;
import com.softeem.mpdemo.service.UserService;
import com.softeem.mpdemo.mapper.UserMapper;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author 86199
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2024-03-06 11:59:45
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService{

    @Override
    public Result login(User user) {

        QueryWrapper<User> query = Wrappers.query(User.class);
        query.eq("username", user.getUsername());
        User a = getOne(query);
        if (Objects.isNull(a)) {
            return Result.fail().setMsg("用户不存在");
        }
        if (a.getStatus() != 0) {
            return Result.fail().setMsg("账号禁用").setCode(1);
        }
        String pwd = SecureUtil.md5(a.getSalt() + user.getPassword());
        user.setPassword(pwd);
        if (Objects.equals(a.getPassword(), user.getPassword())) {
            return Result.ok().setMsg("登陆成功").setData(a);
        }
        return Result.fail().setMsg("密码不正确").setCode(2);
    }

    @Override
    public Result reg(User user) {
        QueryWrapper<User> query = Wrappers.query(User.class);
        query.eq("username", user.getUsername());
        User a = getOne(query);
        if (Objects.nonNull(a)){
            System.out.println("该账号已存在");
            return Result.fail().setMsg("该账号已存在");
        }
        String salt = RandomUtil.randomString(6);
        user.setSalt(salt);
        String pwd = salt + user.getPassword();
        pwd = SecureUtil.md5(pwd);
        user.setPassword(pwd);
        if(save(user)){
            return Result.ok().setMsg("添加成功").setData(user);
        }
        return Result.fail().setMsg("添加失败").setCode(1);
    }

}


